import 'dart:convert';

import 'riki_helper.dart';

typedef OnRikiRouterConvert = T? Function<T extends Object?>(dynamic value);

/// 路由转换器
class RikiRouteConvert {
  /// 转换拓展数组
  static List _converts = <OnRikiRouterConvert>[];

  /// 拓展转换方法
  static void expand(OnRikiRouterConvert convert) {
    if (!_converts.contains(convert)) {
      _converts.add(convert);
    }
  }

  /// 初始化
  static void init() {
    RikiConvert.convert = <T extends Object?>(dynamic value) {
      if (value == null) {
        return null;
      }
      final dynamic output = json.decode(value.toString());
      if (<int>[] is T && output is List<dynamic>) {
        return output.map<int>((dynamic e) => asT<int>(e) as int).toList() as T;
      } else if (<String, dynamic>{} is T && output is Map<dynamic, dynamic>) {
        return output.map<String, dynamic>((dynamic key, dynamic value) => MapEntry<String, dynamic>(key.toString(), value)) as T;
      } else if (<String, String>{} is T && output is Map<dynamic, dynamic>) {
        return output.map<String, String>((dynamic key, dynamic value) => MapEntry<String, String>(key.toString(), value.toString())) as T;
      } else {
        for (OnRikiRouterConvert convert in _converts) {
          T? temp = convert(output);
          if (temp != null) {
            return temp;
          }
        }
      }
      return json.decode(value.toString()) as T?;
    };
  }
}
